<template>
  <view class="dashboard-container">
    <!-- 导航栏 -->
    <view class="navbar">
      <view class="navbar-back" @click="goBack">
        <text class="navbar-back-icon">‹</text>
      </view>
      <view class="navbar-content">
        <view class="navbar-title">停车场管理</view>
        <view class="navbar-subtitle">{{ parkingLotName }}</view>
      </view>
      <view class="navbar-placeholder"></view>
    </view>

    <!-- 统计卡片区域 -->
    <view class="stats-section">
      <!-- 今日订单统计 -->
      <view class="stats-card">
        <view class="stats-header">
          <text class="stats-title">今日订单</text>
          <text class="stats-detail" @click="goToOrderDetail">详情</text>
        </view>
        <view class="stats-content">
          <view class="stats-item">
            <text class="stats-label">暂支付订单</text>
            <text class="stats-value">{{ todayOrders.pending_payment }}</text>
          </view>
          <view class="stats-divider"></view>
          <view class="stats-item">
            <text class="stats-label">预计进场订单</text>
            <text class="stats-value">{{ todayOrders.expected_entry }}</text>
          </view>
          <view class="stats-divider"></view>
          <view class="stats-item">
            <text class="stats-label">预计离场订单</text>
            <text class="stats-value">{{ todayOrders.expected_exit }}</text>
          </view>
        </view>
      </view>

      <!-- 今日业绩统计 -->
      <view class="stats-card">
        <view class="stats-header">
          <text class="stats-title">今日业绩</text>
          <text class="stats-detail" @click="goToRevenueDetail">详情</text>
        </view>
        <view class="stats-content">
          <view class="stats-item">
            <text class="stats-label">实际支付金额</text>
            <text class="stats-value revenue">¥{{ todayRevenue.actual_payment }}</text>
          </view>
          <view class="stats-divider"></view>
          <view class="stats-item">
            <text class="stats-label">预计支付金额</text>
            <text class="stats-value revenue">¥{{ todayRevenue.expected_payment }}</text>
          </view>
          <view class="stats-divider"></view>
          <view class="stats-item">
            <text class="stats-label">成交支付金额</text>
            <text class="stats-value revenue">¥{{ todayRevenue.completed_payment }}</text>
          </view>
        </view>
      </view>

      <!-- 今日车位统计 -->
      <view class="stats-card">
        <view class="stats-header">
          <text class="stats-title">今日车位</text>
          <text class="stats-detail" @click="goToParkingDetail">详情</text>
        </view>
        <view class="stats-content">
          <view class="stats-item">
            <text class="stats-label">库存车位</text>
            <text class="stats-value">{{ todayParking.total_spaces }}</text>
          </view>
          <view class="stats-divider"></view>
          <view class="stats-item">
            <text class="stats-label">总车位数</text>
            <text class="stats-value">{{ todayParking.occupied_spaces }}</text>
          </view>
          <view class="stats-divider"></view>
          <view class="stats-item">
            <text class="stats-label">空车位数</text>
            <text class="stats-value">{{ todayParking.available_spaces }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 功能入口网格 -->
    <view class="function-grid">
      <view class="grid-header">
        <text class="grid-title">小程序异界</text>
        <text class="grid-subtitle">商家联系方式变更提醒</text>
      </view>
      <view class="grid-content">
        <view class="grid-item" @click="goToParkingManagement">
          <view class="grid-icon parking-icon"></view>
          <text class="grid-label">停车场管理</text>
        </view>
        <view class="grid-item" @click="goToReviewManagement">
          <view class="grid-icon review-icon"></view>
          <text class="grid-label">评价管理</text>
        </view>
        <view class="grid-item" @click="goToChangeRequest">
          <view class="grid-icon change-request-icon"></view>
          <text class="grid-label">变更申请</text>
        </view>
        <view class="grid-item" @click="goToBusinessData">
          <view class="grid-icon data-icon"></view>
          <text class="grid-label">经营数据</text>
        </view>
        <view class="grid-item" @click="goToOtherServices">
          <view class="grid-icon service-icon"></view>
          <text class="grid-label">其他服务</text>
        </view>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-overlay">
      <text class="loading-text">加载中...</text>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { request } from '../../utils/request.js'
import { parkingOperatorGuard } from '../../utils/roleGuard.js'

// 响应式数据
const loading = ref(false)
const parkingLotName = ref('')
const todayOrders = ref({
  pending_payment: 0,
  expected_entry: 0,
  expected_exit: 0
})
const todayRevenue = ref({
  actual_payment: '0.00',
  expected_payment: '0.00',
  completed_payment: '0.00'
})
const todayParking = ref({
  total_spaces: 0,
  occupied_spaces: 0,
  available_spaces: 0
})

/**
 * 加载用户角色信息
 */
const loadUserRole = async () => {
  try {
    const response = await request({
      url: '/api/user/role',
      method: 'GET'
    })

    if (response.success && response.data.role_type === 'parking_operator') {
      parkingLotName.value = response.data.parking_lot_name || '未知停车场'
    }
  } catch (error) {
    console.error('获取用户角色失败:', error)
  }
}

/**
 * 加载今日订单统计
 */
const loadTodayOrders = async () => {
  try {
    const response = await request({
      url: '/api/parking-operator/today-orders',
      method: 'GET'
    })

    if (response.success) {
      todayOrders.value = response.data
    }
    return response
  } catch (error) {
    console.error('获取今日订单统计失败:', error)
    throw error
  }
}

/**
 * 加载今日业绩统计
 */
const loadTodayRevenue = async () => {
  try {
    const response = await request({
      url: '/api/parking-operator/today-revenue',
      method: 'GET'
    })

    if (response.success) {
      todayRevenue.value = response.data
    }
    return response
  } catch (error) {
    console.error('获取今日业绩统计失败:', error)
    throw error
  }
}

/**
 * 加载今日车位统计
 */
const loadTodayParking = async () => {
  try {
    const response = await request({
      url: '/api/parking-operator/today-parking',
      method: 'GET'
    })

    if (response.success) {
      todayParking.value = response.data
    }
    return response
  } catch (error) {
    console.error('获取今日车位统计失败:', error)
    throw error
  }
}

/**
 * 加载仪表板数据
 */
const loadDashboardData = async () => {
  loading.value = true
  try {
    // 并行加载所有统计数据
    await Promise.all([
      loadTodayOrders(),
      loadTodayRevenue(),
      loadTodayParking()
    ])

    // 获取停车场名称（从用户角色信息中获取）
    await loadUserRole()

  } catch (error) {
    console.error('加载仪表板数据失败:', error)
    uni.showToast({
      title: '数据加载失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

/**
 * 跳转到订单详情
 */
const goToOrderDetail = () => {
  uni.navigateTo({
    url: '/pages/parking-operator/orders'
  })
}

/**
 * 跳转到业绩详情
 */
const goToRevenueDetail = () => {
  uni.showToast({
    title: '功能开发中',
    icon: 'none'
  })
}

/**
 * 跳转到车位详情
 */
const goToParkingDetail = () => {
  uni.showToast({
    title: '功能开发中',
    icon: 'none'
  })
}

/**
 * 跳转到停车场管理
 */
const goToParkingManagement = () => {
  uni.navigateTo({
    url: '/pages/parking-operator/orders'
  })
}

/**
 * 跳转到变更申请
 */
const goToChangeRequest = () => {
  uni.navigateTo({
    url: '/pages/operator/change-request'
  })
}

/**
 * 跳转到评价管理
 */
const goToReviewManagement = () => {
  uni.navigateTo({
    url: '/pages/parking-operator/reviews'
  })
}

/**
 * 跳转到经营数据
 */
const goToBusinessData = () => {
  uni.showToast({
    title: '功能开发中',
    icon: 'none'
  })
}

/**
 * 跳转到其他服务
 */
const goToOtherServices = () => {
  uni.showToast({
    title: '功能开发中',
    icon: 'none'
  })
}

/**
 * 返回上一页
 */
const goBack = () => {
  uni.navigateBack({
    delta: 1
  })
}

/**
 * 设置停车场管理员信息
 * 由权限守卫调用
 */
const setParkingOperatorInfo = (operatorInfo) => {
  if (operatorInfo) {
    parkingLotName.value = operatorInfo.parking_lot_name || '未知停车场'
  }
}

// 生命周期钩子
onLoad(() => {
  loadDashboardData()
})

onShow(() => {
  // 页面显示时刷新数据
  loadDashboardData()
})

// 应用权限守卫
if (parkingOperatorGuard && parkingOperatorGuard.created) {
  parkingOperatorGuard.created.call({ setParkingOperatorInfo })
}
</script>

<style scoped>
.dashboard-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 导航栏样式 */
.navbar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 60rpx 30rpx 30rpx;
  color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.navbar-back {
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
}

.navbar-back-icon {
  font-size: 48rpx;
  font-weight: bold;
  color: white;
  line-height: 1;
}

.navbar-content {
  flex: 1;
  text-align: center;
}

.navbar-title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.navbar-subtitle {
  font-size: 28rpx;
  opacity: 0.8;
}

.navbar-placeholder {
  width: 80rpx;
  height: 80rpx;
}

/* 统计卡片区域 */
.stats-section {
  padding: 30rpx;
}

.stats-card {
  background: white;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.stats-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.stats-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.stats-detail {
  font-size: 28rpx;
  color: #007aff;
}

.stats-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stats-item {
  flex: 1;
  text-align: center;
}

.stats-label {
  display: block;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.stats-value {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.stats-value.revenue {
  color: #ff6b35;
}

.stats-divider {
  width: 2rpx;
  height: 60rpx;
  background-color: #eee;
  margin: 0 20rpx;
}

/* 功能网格样式 */
.function-grid {
  margin: 30rpx;
  background: white;
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.grid-header {
  margin-bottom: 30rpx;
}

.grid-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.grid-subtitle {
  font-size: 24rpx;
  color: #666;
}

.grid-content {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.grid-item {
  width: 48%;
  text-align: center;
  padding: 30rpx 0;
  margin-bottom: 20rpx;
  border-radius: 15rpx;
  background: #f8f9fa;
}

.grid-icon {
  width: 80rpx;
  height: 80rpx;
  margin: 0 auto 20rpx;
  border-radius: 15rpx;
}

.parking-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.review-icon {
  background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
}

.change-request-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.data-icon {
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
}

.service-icon {
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
}

.grid-label {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

/* 加载状态 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}
</style>